<template>

<!--  拖拽上传的遮罩层-->
  <el-dialog
      title=""
      v-model="containerVisible"
      width="0%"
      modal
      lock-scroll
      :show-close="false"
      destroy-on-close
  >
  </el-dialog>

<!--  上传按钮的弹出层-->
  <el-drawer
      title="上传成功"
      v-model="showProgress"
      direction="btt"
      :modal="false"
      destroy-on-close>
    <el-table
        :data="uploadFileList"
        style="width: 100%">
      <el-table-column
          prop="name"
          label="文件名"
          width="180">
      </el-table-column>
      <el-table-column
          prop="size"
          label="文件大小"
          width="180">
      </el-table-column>
      <el-table-column
          label="上传进度"
      >
        <template #default="scope">
          <el-progress :percentage="scope.row.progress" :color="scope.row.color"></el-progress>
        </template>
      </el-table-column>
    </el-table>
  </el-drawer>

  <el-dialog
      title="上传"
      v-model="uploadFrame"
      width="20%"
  >
    <el-upload
        class="upload-demo"
        drag
        :http-request="upload"
        multiple>
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip">

        </div>
      </template>
    </el-upload>
  </el-dialog>
  <el-container
      ref="container"
      @drop="listenDrop"
      @dragenter="dragEnter"
      @dragleave="dragLeave"
      @dragover.prevent
  >
    <el-aside width="15%">
      <Aside></Aside>
    </el-aside>
    <el-container>
      <el-header>
        <Header></Header>
      </el-header>
      <el-main>
        <div class="layout">
          <div class="layout-item-top">
            <HeaderBtn
                :checked-files="checkedFiles"
                :current-file="currentFile"
                :current-path="currentPath"
                :style="currentStyle"
                :set-mkdir="setMkdir"
                :set-rename="setRename"
                :set-touch="setTouch"
                :share="setShare"
                :deleted="deleted"
                :copy="setCopy"
                :move="setMove"
                :download="download"
                :init="setInit"
                :search="search"
                :upload="setUpload"
                @listenFileList="fileList"
                @changeStyle="changeStyle"
            ></HeaderBtn>
          </div>

          <div class="layout-item-header">
            <div class="fl">
              <div v-if="currentPath.length > 0">
                <el-link
                    type="primary"
                    :underline="false"
                    @click="toBack()"
                >返回上一级<span role="presentation" class="el-breadcrumb__separator">|</span>
                </el-link>

                <el-link
                    type="primary"
                    :underline="false"
                    @click="toRoot()"
                >全部文件<span role="presentation" class="el-breadcrumb__separator">/</span></el-link>

                <el-link
                    :underline="false"
                    v-for="(dir,index) in currentPath" :key="index"
                >
                  {{ dir }}
                  <span role="presentation" class="el-breadcrumb__separator"
                        v-if="index != currentPath.length -1">/</span></el-link>
              </div>
              <el-link :underline="false" v-else>全部文件</el-link>
            </div>
          </div>

          <div class="layout-item-content">
            <Layout
                ref="layout"
                :style="currentStyle"
                :current-type="$route.params.type"
                :current-path="currentPath"
                @listenCheckedFiles="checkedFilesFunc"
                @listenCurrentFile="currentFileFunc"
                @listenFileList="changeFileList"
                @listenCurrentPath="changeCurrentPath"
            ></Layout>
          </div>
        </div>
      </el-main>
    </el-container>
  </el-container>

</template>
<script>

import Aside from '@/components/Aside';
import Header from '@/components/Header';
import Layout from "@/components/Layout";
import HeaderBtn from "@/components/HeaderBtn";

export default {
  name: "Index",
  components: {
    Aside,
    Header,
    Layout,
    HeaderBtn
  },
  data() {
    return {
      containerVisible: false,
      currentStyle: 'table',
      checkedFiles: [],
      currentFile: {},
      currentPath: [],
      searchName: '',
      fileList: [],
      uploadFileList: [],
      showProgress:false,//进度条是否显示
      uploadFrame:false,
    }
  },
  methods: {
    changeStyle(value) {
      this.currentStyle = value;
    },
    checkedFilesFunc(files) {
      if (files != undefined) {
        this.checkedFiles = files;
      }
    },
    currentFileFunc(file) {
      if (file != undefined) {
        this.currentFile = file;
      }
    },
    changeCurrentPath(value) {
      if (value != undefined) {
        this.currentPath = value;
      }
    },
    changeFileList(value) {
      if (value != undefined) {
        this.fileList = value;
      }
    },
    setUpload(){
      this.uploadFrame = true;
    },
    setMkdir() {
      this.$refs.layout.setMkdir();
    },
    setTouch() {
      this.$refs.layout.setTouch();
    },
    setRename() {
      this.$refs.layout.setRename();
    },
    setCopy() {
      //展示目录树
      this.$refs.layout.setCopy();
    },
    setMove() {
      //展示目录树
      this.$refs.layout.setMove();
    },
    setShare() {
      this.$refs.layout.setShare();
    },
    setInit(currentPath, sortField, sortMod) {
      this.$refs.layout.init(currentPath, sortField, sortMod);
    },
    download() {
      this.$refs.layout.download();
    },
    deleted() {
      this.$refs.layout.deleted();
    },
    search(value) {
      if (value) {
        this.$refs.layout.searchName = value;
        this.$refs.layout.init(this.currentPath.join('/'))
      }
    },
    //拖拽监听
    dragLeave(e){
      e.stopPropagation();
      e.preventDefault();  //必填字段
    },
    dragEnter(e){
      e.stopPropagation();
      e.preventDefault();  //必填字段
      this.containerVisible = true;
    },
    listenDrop(e) {
      e.stopPropagation();
      e.preventDefault();  //必填字段
      var that = this, tmp = {};
      that.uploadFileList = [];
      e.dataTransfer.files.forEach(function (file, index) {
        //TODO:这里是重复代码
        tmp = {
          name: file.name,
          size: (file.size/1024)+'KB',
          progress: 0,
          color:that.getColor()
        };
        if (that.uploadFileList.indexOf(tmp) <= -1) {
          that.uploadFileList.push(tmp);
          that.$axios.post('upload/analyse',{
            file_size:file.size,
            file_name:file.name
          }).then(res=>{
            if(res.data.code == 1){
              index = res.data.data.begin;
            }
          })
          that.shardToUpload(0, file, index);
        }
      })
      that.containerVisible = false;
      return false;
    },
    shardToUpload(index, file, eq) {
      let that = this,
          chunkSize = 80 * 1024 * 1024,
          [fName, suffix] = file.name.split('.'),
          single = index * chunkSize,
          total = 0,
          block, blockName, blockFile, formData;
      if (chunkSize < file.size) {
        total = Math.floor(file.size / chunkSize);
      }

      block = file.slice(single, single + chunkSize);
      blockName = `${fName}.${index}.${suffix}`;// 设置分片的 文件名 文件名 . 索引 . 后缀
      blockFile = new File([block], blockName);
      formData = new FormData();

      formData.append('file', blockFile);
      formData.append('number', index);
      formData.append('total', total);
      formData.append('filesize',file.size);
      that.$axios.post('upload/space?currentPath=' + that.currentPath.join('/') + '&name=file', formData, {
        onUploadProgress: (progressEvent) => {
          if (progressEvent.lengthComputable) {
            that.showProgress = true;
            let progress = (((progressEvent.loaded + chunkSize * index) / file.size) * 100 | 0);
            that.uploadFileList[eq].progress = progress > 100 ? 100 : progress;
          }
        },
        headers: {"Content-Type": "multipart/form-data"}
      }).then(res=>{
        if (res.data.code == 1) {
          if (total > index) {
            index += 1;
            that.chunk(index, file, eq)
            return;
          } else if (eq == that.uploadFileList.length - 1 && index == total) {
           that.$refs.layout().init();
          }
        } else {
          that.$message.error(res.data.message);
          that.uploadFileList = [];
          that.showProgress = false;
        }
      })
    },
    getColor() {
      var str = "#";
      var arr = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];
      for (var i=0;i<6;i++){
        var num = parseInt(Math.random()*16); //随机产生0-15之间的一个数
        str += arr[num]; //产生的每个随机数都是一个索引,根据索引找到数组中对应的值,拼接到一起
      }
      return str;
    },
    upload(e){
      let file = e.file,
          that = this,
          tmp = {
            name: file.name,
            size: (file.size/1024)+'KB',
            progress: 0,
            color:this.getColor()
          };
      if (that.uploadFileList.indexOf(tmp) <= -1) {
        var index = 0;
        that.uploadFileList.push(tmp);
        //请求分析判断文件应该从第几片开始上传
        that.$axios.post('upload/analyse',{
          file_size:file.size,
          file_name:file.name
        }).then(res=>{
          if(res.data.code == 1){
            index = res.data.data.begin;
          }
        })
        that.shardToUpload(index, file, 0);
      }
    }
  }
}
</script>

<style scoped>
.el-header {
  color: #333;
  text-align: center;
  line-height: 60px;
  border-bottom: 1px solid #e6e6e6;
}

.el-aside {
  display: block;
  text-align: center;
  height: calc(100vh);
}

.el-main {
  background-color: #f7f7f7;
  /*background-color: #000;*/
}

.layout {
  width: 99%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  flex-wrap: nowrap;
}

.layout .layout-item-top {
  width: 100%;
  padding: 10px;
  background-color: #FFFFFF;
}

.layout .layout-item-header {
  width: calc(100% - 20px);;
  margin: 10px 0;
  padding: 20px;
  background-color: #FFFFFF;

}

.layout .layout-item-content {
  width: calc(100% - 40px);
  padding: 30px;
  background-color: #FFFFFF;
  height: 71vh;
}

</style>
